//
//  JzdxVC.m
//  Lrjh
//
//  Created by jun on 2025/7/21.
//

#import "JzdxVC.h"
#import "JzdxLocationVC.h"
#import "DESCrypts.h"
#import <Foundation/Foundation.h>

@interface JzdxVC ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,JzdxLocationVCDelegate>
@property (weak, nonatomic) IBOutlet UILabel *labLastSign;

@property (weak, nonatomic) IBOutlet UIImageView *ivHead;
@property(nonatomic,copy) NSString *mToken;
@property (weak, nonatomic) IBOutlet UILabel *labLon;
@property (weak, nonatomic) IBOutlet UILabel *labLat;
@property (weak, nonatomic) IBOutlet UILabel *labAddress;
@property (weak, nonatomic) IBOutlet UITextField *tfIp;
@property (weak, nonatomic) IBOutlet UILabel *labImageUrl;
//@property (weak, nonatomic) IBOutlet UILabel *labIpAddress;
@end

@implementation JzdxVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.ivHead.layer.cornerRadius = 60.f;
    self.ivHead.layer.masksToBounds = YES;
    self.title = @"Sign Up";
    
    
    
    
    [self getPublicIPAddress];
    [self findDevice];
    
}

//1.http://202.61.88.14:8093/jzdxapp/v2/findDevice
-(void)findDevice{
    MB_LOADING(@"Progress...");
    NSString *url = @"http://202.61.88.14:8093/jzdxapp/v2/findDevice";
    NSDictionary *param = @{
        @"faceVersion":@"1",
        @"imei":@"23244A8008077910",
        @"version":@"153"
    };
    [LEHttp httpJzdxPost:url token:@"" param:param response:^(NSInteger code, NSString *message, id data) {
        MB_HIDE();
        if(code==200){
            NSDictionary *dataObj = data[@"data"];
            NSString *token = dataObj[@"token"];
            NSDictionary *zjtmm = dataObj[@"zjtmm"];
            long long signtime = [zjtmm[@"signtime"] longLongValue];
            
            NSString *time = [self formatMillisecondTimestamp:signtime];
            NSLog(@"===>time==%@",time);
            self.labLastSign.text = [NSString stringWithFormat:@"Last Sign:%@",time];
            [self login:token];
        }else{
            [self showTipInfo:message okClick:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    }];
}

- (NSString *)formatMillisecondTimestamp:(long long)timestamp {
    NSTimeInterval seconds = timestamp / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}

- (void)getPublicIPAddress {
    NSURL *url = [NSURL URLWithString:@"https://checkip.amazonaws.com"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url
                                        completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error: %@", error.localizedDescription);
            return;
        }
        if (data) {
            NSString *ip = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            ip = [ip stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.tfIp.text = ip;
            });
        }
    }];
    [task resume];
}

-(void)login:(NSString*)token{
    MB_LOADING(@"Logining...");
    NSString *url = @"http://202.61.88.14:8093/jzdxapp/v2/login";
    
    NSString *passowrd = [DESCrypts Encrypt:@"ChmLzj123"];
    NSLog(@"====>密码加密==>%@",passowrd);
    NSString *imeiEnd = [DESCrypts Encrypt:@"23244A8008077910"];
    NSLog(@"===IMEI加密==>%@",imeiEnd);
    NSString *idStr = [DESCrypts Encrypt:@"511124198810136617"];
    NSLog(@"====id加密==>%@",idStr);
    
    
    
    
//    NSDictionary *param = @{
//        @"password":@"9359431eccd954fc7572ff24061b9071",
//        @"imei":@"fc21d6fa1876855442cb8e03b7d986b687dd6d2e99061045",
//        @"id":@"b827f386bc1ebcbf48bd4694068dd80df21f5e924dfd5bd7",
//        @"type":@"0"
//    };
    NSDictionary *param = @{
        @"password":passowrd,
        @"imei":imeiEnd,
        @"id":idStr,
        @"type":@"0"
    };
    [LEHttp httpJzdxPost:url token:token param:param response:^(NSInteger code, NSString *message, id data) {
        MB_HIDE();
        if(code==200){
            NSDictionary *dataObj = data[@"data"];
            self.mToken = dataObj[@"token"];
            NSLog(@"====>登录成功==%@",self.mToken);
        }else{
            [self showTipInfo:message okClick:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    }];
}


- (IBAction)onChoose:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    picker.delegate = self;
    picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff;
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:YES completion:nil];
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *normalizedImage = [self normalizedImage:originalImage];
        UIImage *flippedImage = [self flipImageHorizontally:normalizedImage];
        UIImage *resizedImage = [self resizeImage:flippedImage toSize:CGSizeMake(720, 1280)];
        NSData *compressedData = [self compressImage:resizedImage maxSizeKB:200];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (compressedData) {
                [self upImageData:compressedData];
            }
        });
    });
}

- (UIImage *)normalizedImage:(UIImage *)image {
    if (image.imageOrientation == UIImageOrientationUp) return image;
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

- (UIImage *)flipImageHorizontally:(UIImage *)image {
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, image.size.width, 0);
    CGContextScaleCTM(context, -1.0, 1.0);
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    UIImage *flippedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return flippedImage;
}

- (UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)targetSize {
    UIGraphicsBeginImageContextWithOptions(targetSize, NO, 1.0);
    CGRect rect = CGRectMake(0, 0, targetSize.width, targetSize.height);
    CGFloat ratio = MAX(targetSize.width / image.size.width, targetSize.height / image.size.height);
    CGSize scaledSize = CGSizeMake(image.size.width * ratio, image.size.height * ratio);
    CGRect scaledRect = CGRectMake(
        (targetSize.width - scaledSize.width) / 2.0,
        (targetSize.height - scaledSize.height) / 2.0,
        scaledSize.width,
        scaledSize.height
    );
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
    [path addClip];
    [image drawInRect:scaledRect];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resizedImage;
}

- (NSData *)compressImage:(UIImage *)image maxSizeKB:(NSInteger)maxSizeKB {
    CGFloat compression = 0.9f;
    CGFloat minCompression = 0.1f;
    NSInteger maxByte = maxSizeKB * 1024;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while (imageData.length > maxByte && compression > minCompression) {
        compression -= 0.1f;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    if (imageData.length > maxByte) {
        UIImage *tempImage = [UIImage imageWithData:imageData];
        CGFloat ratio = sqrtf((CGFloat)maxByte / (CGFloat)imageData.length);
        CGSize newSize = CGSizeMake((NSInteger)(image.size.width * ratio), (NSInteger)(image.size.height * ratio));
        tempImage = [self resizeImage:tempImage toSize:newSize];
        imageData = UIImageJPEGRepresentation(tempImage, 0.9);
    }
    return imageData.length <= maxByte ? imageData : nil;
}


- (void)upImageData:(NSData *)imageData {
    UIImage *image = [UIImage imageWithData:imageData];
    self.ivHead.image = image;
    NSString *url = @"http://202.61.88.14:8093/jzdxapp/v2/upQdfile";
    MB_LOADING(@"Uploading...");
    [LEHttp httpUpJzdxImage:url img:image key:@"file" token:self.mToken response:^(NSInteger code, NSString *message, id data) {
        MB_HIDE();
        if(code==200){
            self.labImageUrl.text = [NSString stringWithFormat:@"%@",data[@"data"]];
        }else{
            [self showTipInfo:message okClick:nil];
        }
    }];
}


- (IBAction)onAddress:(id)sender {
    JzdxLocationVC *vc = [JzdxLocationVC new];
    vc.delegate =self;
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)onLocation:(NSString *)lat lon:(NSString *)lon address:(NSString *)address{
    self.labLat.text = lat;
    self.labLon.text = lon;
    self.labAddress.text = address;
}

/**
 http://202.61.88.14:8093/jzdxapp/v2/ryqd
签到
 filename=2025_07_21_15_28_54_200_1_w.jpg&dwdz=中国四川省成都市武侯区桂溪街道天府四街&ip=218.88.69.240&latitude=30.541601&longitude=104.059903
 */

-(void)ryqd{
    NSString *filename = self.labImageUrl.text;
    if(ISEmpty(filename)){
        return;
    }
    NSString *latitude = self.labLat.text;
    if(ISEmpty(latitude)){
        return;
    }
    
    NSString *longitude = self.labLon.text;
    if(ISEmpty(longitude)){
        return;
    }
    
    NSString *dwdz = self.labAddress.text;
    if(ISEmpty(dwdz)){
        return;
    }
    
    NSString *ip = self.tfIp.text;
    if(ISEmpty(ip)){
        return;
    }
    

    NSDictionary *param  = @{
        @"filename":filename,
        @"dwdz":dwdz,
        @"ip":ip,
        @"latitude":latitude,
        @"longitude":longitude
    };
    [self.view endEditing:YES];
    NSLog(@"%@",param);
    
    MB_LOADING(@"Progressing...");
    NSString *url= @"http://202.61.88.14:8093/jzdxapp/v2/ryqd";
    WS(weakSelf);
    NSLog(@"%@",param);
    [LEHttp httpJzdxPost:url token:self.mToken param:param response:^(NSInteger code, NSString *message, id data) {
        MB_HIDE();
        if(code==200){
            [weakSelf showTipInfo:@"Sign Success!" okClick:^{
                [weakSelf save];
            }];
        }else{
            [weakSelf showTipInfo:message okClick:nil];
        }
    }];
}


- (IBAction)onConfirm:(id)sender {
    [self ryqd];
}

/**
 http://202.61.88.14:8093/jzdxdwdata/save
 上报位置
 sjly=3&address中国四川省成都市武侯区桂溪街道天府四街&imei=fc21d6fa1876855442cb8e03b7d986b687dd6d2e99061045&lon=b43f020e6b78157a343cc5b359e80b4d&time=1753089624320&lat=fa2b68903beafea91ba29fef8814a1b5
 */

-(void)save{
    
    NSString *latitude = self.labLat.text;
    if(ISEmpty(latitude)){
        return;
    }
    
    NSString *lat = [DESCrypts Encrypt:latitude];
    
    NSString *longitude = self.labLon.text;
    if(ISEmpty(longitude)){
        return;
    }
    
    NSString *lon = [DESCrypts Encrypt:longitude];
    
    NSString *address = self.labAddress.text;
    if(ISEmpty(address)){
        return;
    }
    
    NSString *imei = @"fc21d6fa1876855442cb8e03b7d986b687dd6d2e99061045";
    
    NSString *time = [NSString stringWithFormat:@"%lld", (long long)([[NSDate date] timeIntervalSince1970] * 1000)];
    

    NSDictionary *param= @{
        @"sjly":@"3",
        @"address":address,
        @"imei":imei,
        @"lon":lat,
        @"time":time,
        @"lat":lon
    };
    
    NSLog(@"%@",param);
    

    MB_LOADING(@"Saveing...");
    NSString *url= @"http://202.61.88.14:8093/jzdxdwdata/save";
    WS(weakSelf);
    NSLog(@"%@",param);
    [LEHttp httpJzdxPost:url token:self.mToken param:param response:^(NSInteger code, NSString *message, id data) {
        MB_HIDE();
        if(code==200){
            [weakSelf showTipInfo:@"Save 3 Success!" okClick:^{
                [weakSelf save000];
            }];
        }else{
            [weakSelf showTipInfo:message okClick:nil];
        }
    }];
}


-(void)save000{
    
    NSString *latitude = self.labLat.text;
    if(ISEmpty(latitude)){
        return;
    }
    
    NSString *lat = [DESCrypts Encrypt:latitude];
    
    NSString *longitude = self.labLon.text;
    if(ISEmpty(longitude)){
        return;
    }
    
    NSString *lon = [DESCrypts Encrypt:longitude];
    
    NSString *address = self.labAddress.text;
    if(ISEmpty(address)){
        return;
    }
    
    NSString *imei = @"fc21d6fa1876855442cb8e03b7d986b687dd6d2e99061045";
    
    NSString *time = [NSString stringWithFormat:@"%lld", (long long)([[NSDate date] timeIntervalSince1970] * 1000)];
    

    NSDictionary *param= @{
        @"sjly":@"0",
        @"address":address,
        @"imei":imei,
        @"lon":lat,
        @"time":time,
        @"lat":lon
    };
    
    NSLog(@"%@",param);
    

    MB_LOADING(@"Saveing...");
    NSString *url= @"http://202.61.88.14:8093/jzdxdwdata/save";
    WS(weakSelf);
    NSLog(@"%@",param);
    [LEHttp httpJzdxPost:url token:self.mToken param:param response:^(NSInteger code, NSString *message, id data) {
        MB_HIDE();
        if(code==200){
            [weakSelf showTipInfo:@"Save 0 Success!" okClick:^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [weakSelf showTipInfo:message okClick:nil];
        }
    }];
}

@end
